<template>
  <span>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
      append-to-body >
      <slot></slot>
      <span slot="footer" class="dialog-footer">
        <el-button @click="doCancel">取 消</el-button>
        <el-button type="primary" @click="doSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </span>
</template>

<script>

import {del, post, update} from '../components/HttpUtil'

export default {
  name: 'DialogFormCpt',

  props: {
    dialogVisible: {},
    title: '',
    content: {},
    url: '',
    method: '',
    width: '',
  },
  data() {
    return {}
  },
  methods: {
    handleClose() {
      this.dialogVisible = !this.dialogVisible
      this.$emit('close', this.dialogVisible)

    },
    doSubmit() {
      this.dialogVisible = !this.dialogVisible
      this.$emit('close', this.dialogVisible)
      if (this.method === 'post') {
        post(this.url, this.$store.state.token, this.content)
          .then(res => {
            this.$emit('doSubmit')
          })
          .catch(e => {
            console.error(e)
          })
      } else if (this.method === 'update') {
        this.url = this.url + this.content.id
        update(this.url, this.$store.state.token, this.content)
          .then(res => {
            this.$emit('doSubmit')
          })
          .catch(e => {
            console.error(e)
          })
      } else if (this.method === 'delete') {
        del(this.url, this.$store.state.token)
          .then(res => {
            this.$emit('doSubmit')
          })
          .catch(e => {
            console.error(e)
          })
      }

    },
    doCancel() {
      this.dialogVisible = !this.dialogVisible
      this.$emit('close', this.dialogVisible)
    }

  },

  watch: {
    dataSource: {
      immediate: true,
      handler(val) {
        this.content = val
      }
    }
  }

}
</script>

<style scoped>
</style>
